import React from 'react';
import { useSelector, useDispatch } from 'react-redux'
import {useLocation, useNavigate} from 'react-router-dom'
import { Space,Tag } from 'antd'
import { closeTab,setCurrentMenu } from '../../store/reducers/tab'
import './index.css'
const CommonTag = () =>{
    const dispatch = useDispatch()
    const action = useLocation()
    const navigate = useNavigate()
    const tabList = useSelector(state => state.tab.tabList)
    const currentMenu  = useSelector(state => state.tab.currentMenu)
    const handleClose = (tag,index) =>{
        let length = tabList.length  - 1
        dispatch(closeTab(tag))
        if(tag.path !== action.pathname) {
            return
        }
        // 关闭的是最后一个
        if(index === length) {
            const curData = tabList[index - 1]
            dispatch(setCurrentMenu(curData))
            navigate(curData.path)
        } else {
            // 如果tag存在一个数据
            if(tabList.length > 1) {
                // 下一个
                const nextData = tabList[index + 1]
                dispatch(setCurrentMenu(nextData))
                navigate(nextData.path)
            }
        }
    }
    const handleChange = menuTag => {
        dispatch(setCurrentMenu(menuTag))
        navigate(menuTag.path)
    }
    // tag
    const setTag = (flag,item,index) => {
      return (
          flag ?
              <Tag className="tag" key={item.path}  color="#55acee" closeIcon onClose={()=> handleClose(item,index)} >{ item.label }</Tag>
              :
              <Tag className="tag" key={item.path} onClick={() => handleChange(item)} key={item.name} >{ item.label }</Tag>
      )
    }
    return (
        <Space className="common-tag" size={[0,8]} wrap>
            {/*<Tag>首页</Tag>*/}
            {/*<Tag color="#55acee" closeIcon onClose={()=> handleClose()}>*/}
            {/*    用户列表*/}
            {/*</Tag>*/}
            {
              currentMenu.name &&  tabList.map((item,index) => setTag(item.path ===currentMenu.path, item,index))
            }
        </Space>
    )
}

export default CommonTag;
